package com.kfm.domain;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kfm.util.GrantedAuthorityDeserializer;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "sys_user")
public class SysUser implements Serializable, UserDetails {
    @Id
    @Column(name = "id", nullable = false, length = 32, precision = 0)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username", length = 20, precision = 1)
    private String username;

    @Column(name = "password", nullable = false, length = 60, precision = 2)
    private String password;

    @Column(name = "create_time")
    private Date createTime;

    @Column(name = "update_time", precision = 4)
    private Date updateTime;

    @Column(name = "state", precision = 5)
    private Integer state;

    /**
     * JPA 新增时自动设置创建时间
     */
    @PrePersist
    public void prePersist() {
        this.createTime = new Date();
        this.state = 1;
    }

    /**
     * JPA 更新时自动设置更新时间
     */
    @PreUpdate
    public void preUpdate() {
        this.updateTime = new Date();
    }


    /**
     * authorities 是一个权限集合，可以用于存储用户的权限信息
     * 此字段不是数据库字段，用于封装用户权限
     * getAuthorities() 方法返回用户的所有权限
     *
     * @JsonDeserialize(using = GrantedAuthorityDeserializer.class)
     * 由于 SimpleGrantedAuthority 没有无参构造函数，所以需要自定义反序列化器
     */
    @Transient
    @JsonDeserialize(using = GrantedAuthorityDeserializer.class)
    private Set<? extends GrantedAuthority> authorities;

    @Transient
    private boolean accountNonExpired;

    @Transient
    private boolean accountNonLocked;

    @Transient
    private boolean credentialsNonExpired;

    @Transient
    private boolean enabled;

    /**
     * 用户的账号是否未过期
     * @return true 表示账号未过期
     */
    public boolean isAccountNonExpired() {
        return this.state == 1;
    }

    /**
     * 用户的账号是否未锁定
     * @return true 账号未锁定
     */
    public boolean isAccountNonLocked() {
        return this.state == 1;
    }

    /**
     * 用户的密码是否未过期
     * @return true 密码未过期
     */
    public boolean isCredentialsNonExpired() {
        return this.state == 1;
    }

    /**
     * 用户是否可用
     * @return true 账号状态可用
     */
    public boolean isEnabled() {
        return this.state == 1;
    }

}